# -*- coding: utf-8 -*-
from smtplib import SMTP,SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename
from ..utilities.environment_and_platform import environment_initialisation
from ..utilities.csv_and_json_serialisation import load_yaml


class messenger(object):
	'''信使类，专门发邮件'''
	
	def __init__(self,*args,**kwargs):
		super(messenger, self).__init__()
		if not kwargs.__contains__('environment_pack'):
			environment_initialisation(self)
			pass
		
		config_filename=self.environment_pack['instance_path']['config_file_dir']+"config.yml"
		self.config=load_yaml(config_filename)
		
		pass
	
	def __login(self):
		smtp_obj=SMTP_SSL() if self.config['if_ssl'] else SMTP()
		smtp_obj.connect(self.config['smtp_server'], self.config['smtp_port'])
		smtp_obj.login(self.config['username'], self.config['passwd'])
		return smtp_obj
	
	def send_mail(self,sendto,sender=None,mail_title='',mail_text='',attachment_file=None):
		'''发送邮件，如果有附件，附带附件'''
		
		smtp_instance=self.__login()
		
		testing_mail=MIMEMultipart()
		testing_mail["From"]=self.config['sender_address' ]
		testing_mail["To"]=";".join(sendto)+';'
		testing_mail['Subject']=mail_title
		
		mail_text_part=MIMEText(mail_text)
		testing_mail.attach(mail_text_part)
		
		if attachment_file:
			with open(attachment_file,'rb') as file_attachment:
				all_bins=file_attachment.read()
				binary_part=MIMEApplication(all_bins)
				binary_part.add_header('Content-Disposition', 'attachment', filename=basename(attachment_file))
				testing_mail.attach(binary_part)
				pass
			
		
		result=smtp_instance.sendmail(self.config['sender_address' ],sendto,testing_mail.as_string())
		smtp_instance.close()
		
		pass
	pass

'''
用例：
testing_messenger=messenger()
testing_messenger.send_mail(sendto=["snake3342@aliyun.com","snake3342@qq.com"],
                            mail_title="测试发送",
                            mail_text="测试正文",
                            attachment_file=C:\\abc.txt)#附件，没有可以不填
'''